﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using Sunboxsoft.WinForm;
using Sunboxsoft.Common;
using System.Windows.Forms;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using BasesWebRef = Sunboxsoft.ASMS.Client.Domain.BasesWebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using LocalService = Sunboxsoft.ASMS.Client.Domain.LocalService;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Edit
{
    /// <summary>
    /// 修改客户
    /// </summary>
    public partial class UpdateCustomerView : UserControl, IView
    {
        Guid _customerId;
        WebRef.VCustomer _vCustomer = null;
        Promise _promise = new Promise();
        Common.Validations.TextEditIdNumberValidation _idNumberValidation = null;
        public UpdateCustomerView()
        {
            InitializeComponent();
            _idNumberValidation = new Common.Validations.TextEditIdNumberValidation(ctlEditIdNumber, true);
            ValidationManager.Register(this, _idNumberValidation);
            ValidationManager.Register(this, new Common.Validations.TextEditEMailValidation(txtEMail));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(ctlEditName, "姓名", false));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(ctlEditAddress, "详细地址", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNumberValidation(txtQQ, "QQ号码", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(txtWebChat, "微信号码", true));
        }
        public UpdateCustomerView(Guid customerId)
            : this()
        {
            this._customerId = customerId;
        }
        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            if (UIContext.Current.ViewContext.Stack.HasAnyBackground())
            {
                // 在当前视图后面还存在别的视图,显示取消按钮
                collection.AddAction(new ActionNode("reset", Resources.isReset, "重置", ctlBtnResetClick))
                    .AddAction(new ActionNode("save", Resources.isOK, "保存", ctlBtnSave_Click))
                    .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", ctlBtnCancel_Click));
            }
            else
            {
                collection.AddAction("reset", "重置", ctlBtnResetClick)
                    .AddAction(new ActionNode("save", Resources.isOK, "保存", ctlBtnSave_Click));
            }
        }
        public void Resume(ViewResumeArgs args)
        {
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    LookUpEditUtil.BindIntCodeTextItem(this.ctlLookUpGenders, Domain.Constant.Genders.Enumerate(), null, true);
                    _promise.Resolve();
                }));
            })
            .Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(this.ctlSelectLookUpEditCustomerType, _promise, Domain.Constant.MasterDataCodes.CustumerType);
            })
                .Then(() =>
            {
                SearchLookUpEditUtil.BindVStaffPosition(this.ctlSearchLookUpEditSalesManager, _promise, Domain.Constant.StaffPosts.SalesManager);
            }
            ).Then(GetVCustomer).Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(ctlLookUpCountry, _promise, Domain.Constant.MasterDataCodes.Country,
                    null, null, true, true);
            })
            .Run(null);
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("修改客户");
        }
        #endregion

        #region Method
        private void GetVCustomer()
        {
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<WebRef.VCustomer> result = new Service.GetService().GetCustomer(_customerId);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        _vCustomer = result.Data;
                        this.ctlEditTelephone.Text = result.Data.Telephone;
                        this.ctlEditName.Text = result.Data.Name;
                        this.ctlEditIdNumber.Text = result.Data.IdNumber;
                        ctlSelectLookUpEditCustomerType.SelectEMasterDataItem(result.Data.Type);
                        if (result.Data.Gender == Domain.Constant.Genders.Male)
                        {
                            this.ctlLookUpGenders.EditValue = Domain.Constant.Genders.MaleItem;
                        }
                        else if (result.Data.Gender == Domain.Constant.Genders.Female)
                        {
                            this.ctlLookUpGenders.EditValue = Domain.Constant.Genders.FemaleItem;
                        }
                        else
                        {
                            this.ctlLookUpGenders.EditValue = null;
                        }
                        if (result.Data.IsCredit)
                        {
                            this.ctlListIsOnTrust.SelectedIndex = 0;
                        }
                        else
                        {
                            this.ctlListIsOnTrust.SelectedIndex = 1;
                        }
                        if (result.Data.SalesManagerId != null)
                        {
                            SearchLookUpEditUtil.SelectVStaffPosition(ctlSearchLookUpEditSalesManager, new Guid(result.Data.SalesManagerId.ToString()));
                        }
                        this.ctlEditAddress.Text = result.Data.Address;
                        this.ctlDateBirthday.Text = result.Data.Birthday.ToString();
                        ctlEditVIPNumber.Text = result.Data.VIPNumber;
                        ctlEditVIPLevel.Text = result.Data.VIPLevelText;
                        txtEMail.Text = result.Data.EMail;
                        txtQQ.Text = result.Data.QQ;
                        txtWebChat.Text = result.Data.Wechat;
                        if (result.Data.Type == "CT0002")
                        {
                            ValidationManager.Unregister(this, _idNumberValidation);
                        }
                        else
                        {
                            ValidationManager.Register(this, _idNumberValidation);
                        }
                        _promise.Resolve();
                    }
                    else
                    {
                        MessageBox.Show(result.Message);
                        _promise.Reject();
                    }
                    this.HideMask();
                }));
            });
            
        }
        /// <summary>
        /// 修改客户
        /// </summary>
        private void UpdateCustomer()
        {
            WebRef.ECustomer model = new WebRef.ECustomer();
            model.Id = _customerId;
            model.Name = this.ctlEditName.EditValue.ToString();
            model.Telephone = this.ctlEditTelephone.EditValue.ToString();
            model.EMail = this.txtEMail.Text.Trim();
            if (this.ctlEditIdNumber.EditValue != null)
            {
                model.IdNumber = this.ctlEditIdNumber.EditValue.ToString();
            }
            model.Country = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpCountry).GetCode();
            model.Province = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpProvince).GetCode();
            model.City = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpCity).GetCode();
            model.District = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpDistrict).GetCode();
            model.Address = this.ctlEditAddress.Text.Trim();
            model.QQ = this.txtQQ.EditValue == null ? null : this.txtQQ.EditValue.ToString();
            model.Wechat = this.txtWebChat.EditValue == null ? null : this.txtWebChat.EditValue.ToString();
            if (!string.IsNullOrEmpty(this.ctlDateBirthday.EditValue.ToString()))
            {
                model.Birthday = Convert.ToDateTime(this.ctlDateBirthday.EditValue);
            }
            model.IsCredit = ctlListIsOnTrust.EditValue.ToString().Equals("是") ? true : false;
            WebRef.VStaffPosition vStaffPosition = SearchLookUpEditUtil.GetSelectedValue<WebRef.VStaffPosition>(this.ctlSearchLookUpEditSalesManager);
            if (vStaffPosition != null)
            {
                model.SalesManagerId = vStaffPosition.StaffId;
            }
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.UpdateService().UpdateCustomer(_customerId, model);
                this.BeginInvoke(new Action(() =>
                {
                    this.HideMask();
                    if (result.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, null);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ctlBtnResetClick(object sender, object e)
        {
            if (!string.IsNullOrEmpty(ctlEditTelephone.Text))
            {
                if (!UIContext.Current.ViewManager.ShowQuestion("是否重置，重新输入客户信息?"))
                {
                    return;
                }
            }
            ctlEditName.EditValue = null;
            ctlEditIdNumber.EditValue = null;
            txtEMail.EditValue = null;
            ctlDateBirthday.EditValue = null;
            
            ctlEditName.Enabled = true;
            ctlEditIdNumber.Enabled = true;
            txtEMail.Enabled = true;
            ctlDateBirthday.Enabled = true;

            ctlEditName.Focus();
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlBtnSave_Click(object sender, object e)
        {
            string message = null;
            if (ValidationManager.Validate(this, out message))
            {
                UpdateCustomer();
            }
            else
            {
                UIContext.Current.ViewManager.ShowError(message);
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlBtnCancel_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(false, null);
        }
        /// <summary>
        /// 根据选择国家获取省份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lupCountry_EditValueChanged(object sender, EventArgs e)
        {
            Promise promise = new Promise();
            promise.Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(this.ctlLookUpProvince, promise,
                   Domain.Constant.MasterDataCodes.Province,
                   SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpCountry).GetCode(),
                   null,
                   false, true);
            }).Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    if (_vCustomer != null)
                    {
                        ctlLookUpProvince.SelectEMasterDataItem(_vCustomer.Province);
                    }
                    promise.Resolve();
                }));
            }).Run();
        }
        /// <summary>
        /// 根据选择省获取市
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lupProvince_EditValueChanged(object sender, EventArgs e)
        {
            Promise promise = new Promise();
            promise.Then(() =>
           {
               SearchLookUpEditUtil.BindEMasterDataItem(this.ctlLookUpCity, promise,
                   Domain.Constant.MasterDataCodes.City,
                    SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpProvince).GetCode(),
                    null, false, true);
           }).Then(() =>
           {
               this.BeginInvoke(new Action(() =>
               {
                   if (_vCustomer != null)
                   {
                       ctlLookUpCity.SelectEMasterDataItem(_vCustomer.City);
                   }
                   promise.Resolve();
               }));
           }).Run();
        }
        /// <summary>
        /// 根据市获取区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lupCity_EditValueChanged(object sender, EventArgs e)
        {
            if (this.ctlLookUpCity.EditValue == null)
                return;
            Promise promise = new Promise();
            promise.Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(this.ctlLookUpDistrict, promise,
                    Domain.Constant.MasterDataCodes.District,
                    SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpCity).GetCode(), null, false, true);
            }).Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    if (_vCustomer != null)
                    {
                        ctlLookUpDistrict.SelectEMasterDataItem(_vCustomer.District);
                    }
                    promise.Resolve();
                }));
            }).Run();
        }
        #endregion
    }
}
